import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

interface Message {
  id: string;
  text: string;
  sender: 'user' | 'ai';
  timestamp: Date;
}

interface Conversation {
  roleId: number;
  roleName: string;
  roleImage: string;
  messages: Message[];
  timestamp: Date;
}

interface VoiceChatProps {
  selectedRole: any;
}

export default function VoiceChat({ selectedRole }: VoiceChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isListening, setIsListening] = useState(false);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [conversationHistory, setConversationHistory] = useState<Conversation[]>([]);
  const [selectedConversationIndex, setSelectedConversationIndex] = useState<number | null>(null);

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === now.toDateString()) {
      return `今天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
    } else if (date.toDateString() === yesterday.toDateString()) {
      return `昨天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
    } else {
      return date.toLocaleDateString();
    }
  };

  // 加载历史会话
  const loadConversationHistory = () => {
    try {
      const savedHistory = localStorage.getItem('conversationHistory');
      if (savedHistory) {
        const parsedHistory = JSON.parse(savedHistory);
        // 将时间戳字符串转换为Date对象
        const historyWithDates = parsedHistory.map((conversation: any) => ({
          ...conversation,
          timestamp: new Date(conversation.timestamp),
          messages: conversation.messages.map((message: any) => ({
            ...message,
            timestamp: new Date(message.timestamp)
          }))
        }));
        setConversationHistory(historyWithDates);
      }
    } catch (error) {
      console.error('Failed to load conversation history', error);
    }
  };

  // 保存会话历史
  const saveConversationHistory = () => {
    try {
      localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
    } catch (error) {
      console.error('Failed to save conversation history', error);
    }
  };

  // 加载特定会话
  const loadConversation = (index: number) => {
    const conversation = conversationHistory[index];
    if (conversation) {
      // 将时间戳字符串转换为Date对象
      const messagesWithDates = conversation.messages.map((message: any) => ({
        ...message,
        timestamp: new Date(message.timestamp)
      }));
      setMessages(messagesWithDates);
      setSelectedConversationIndex(index);
    }
  };

  // 初始化加载会话历史
  useEffect(() => {
    loadConversationHistory();
  }, []);

  // 当选择新角色时创建新会话
  useEffect(() => {
    if (selectedRole) {
      // 检查是否已有该角色的会话
      const existingIndex = conversationHistory.findIndex(
        conv => conv.roleId === selectedRole.id
      );

      if (existingIndex >= 0) {
        // 如果已有会话，加载它
        loadConversation(existingIndex);
      } else {
        // 如果没有，创建新会话
        const welcomeMessage: Message = {
          id: 'welcome',
          text: `你好！我是${selectedRole.name}。很高兴能和你聊天，有什么我可以帮助你的吗？`,
          sender: 'ai',
          timestamp: new Date()
        };
        
        setMessages([welcomeMessage]);
        setSelectedConversationIndex(null);
      }
    }
  }, [selectedRole]);

  // 当消息更新时保存会话
  useEffect(() => {
    if (selectedRole && messages.length > 0) {
      const newConversation: Conversation = {
        roleId: selectedRole.id,
        roleName: selectedRole.name,
        roleImage: selectedRole.image,
        messages: messages,
        timestamp: new Date()
      };

      setConversationHistory(prev => {
        // 查找是否已有该角色的会话
        const existingIndex = prev.findIndex(conv => conv.roleId === selectedRole.id);
        let updatedHistory;

        if (existingIndex >= 0) {
          // 更新现有会话
          updatedHistory = [...prev];
          updatedHistory[existingIndex] = newConversation;
        } else {
          // 添加新会话
          updatedHistory = [newConversation, ...prev].slice(0, 10); // 限制最多保存10个会话
        }

        // 保存到localStorage
        saveConversationHistory();
        return updatedHistory;
      });
    }
  }, [messages, selectedRole]);

  const startListening = () => {
    if (!selectedRole) return;
    
    setIsListening(true);
    
    // 模拟语音识别
    setTimeout(() => {
      setIsListening(false);
      const userMessage: Message = {
        id: Date.now().toString(),
        text: "这是一条模拟的语音输入消息。",
        sender: 'user',
        timestamp: new Date()
      };
      setMessages(prev => [...prev, userMessage]);
      
      // 模拟AI思考和回复
      setTimeout(() => {
        generateAIResponse(userMessage.text);
      }, 1500);
    }, 3000);
  };

  const generateAIResponse = (userText: string) => {
    if (!selectedRole) return;
    
    setIsLoading(true);
    
    // 模拟AI回复生成
    setTimeout(() => {
      setIsLoading(false);
      setIsSpeaking(true);
      
      const responses = [
        `谢谢你的消息！作为${selectedRole.name}，我认为${userText}这个问题很有意思。`,
        `关于${userText}，我的看法是这样的...`,
        `这是一个很好的观点！从我的角度来看，${userText}涉及到很多方面。`,
        `我明白你的意思。在我的经验中，${userText}通常需要从多个角度考虑。`
      ];
      
      const randomResponse = responses[Math.floor(Math.random() * responses.length)];
      
      const aiMessage: Message = {
        id: Date.now().toString(),
        text: randomResponse,
        sender: 'ai',
        timestamp: new Date()
      };
      
      setMessages(prev => [...prev, aiMessage]);
      
      // 模拟语音播放
      setTimeout(() => {
        setIsSpeaking(false);
      }, 5000);
    }, 2000);
  };

  const sendTextMessage = () => {
    if (!inputText.trim() || !selectedRole) return;
    
    const userMessage: Message = {
      id: Date.now().toString(),
      text: inputText,
      sender: 'user',
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, userMessage]);
    setInputText('');
    generateAIResponse(inputText);
  };

  if (!selectedRole) {
    return (
      <div className="bg-white rounded-2xl shadow-lg p-12 text-center">
        <div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <i className="fa-solid fa-microphone-slash text-blue-400 text-2xl"></i>
        </div>
        <h3 className="text-xl font-semibold text-gray-800 mb-2">请选择一个角色开始聊天</h3>
        <p className="text-gray-500">从搜索结果或角色列表中选择一个角色，即可开始与AI角色对话</p>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-2xl shadow-lg overflow-hidden flex flex-col h-full">
      <div className="flex flex-col md:flex-row h-full">
         {/* 历史会话记录面板 */}
         <div className="w-full md:w-64 border-r border-gray-100 p-4 hidden md:block">
           <h3 className="text-lg font-semibold text-gray-800 mb-4">历史会话</h3>
           <div className="space-y-3 max-h-[calc(100vh-300px)] overflow-y-auto">
             {conversationHistory.length > 0 ? (
               conversationHistory.map((conversation, index) => (
                 <div 
                   key={index} 
                   className={`p-3 rounded-xl cursor-pointer transition-colors ${
                     selectedConversationIndex === index ? 'bg-blue-100' : 'bg-gray-50 hover:bg-blue-50'
                   }`}
                   onClick={() => loadConversation(index)}
                 >
                   <p className="font-medium text-gray-800">{conversation.roleName}</p>
                   <p className="text-xs text-gray-500">{formatDate(conversation.timestamp)}</p>
                 </div>
               ))
             ) : (
               <div className="text-center py-6 text-gray-500 text-sm">
                 <i className="fa-solid fa-comments mb-2 block text-2xl opacity-30"></i>
                 暂无历史会话
               </div>
             )}
           </div>
         </div>
        
        {/* 主聊天区域 */}
        <div className="flex-grow flex flex-col">
          <div className="p-6 border-b border-gray-100">
            <h2 className="text-xl font-bold text-gray-800">与 {selectedRole.name} 聊天</h2>
          </div>
          
          <div className="flex-grow overflow-y-auto p-6 space-y-6" style={{ maxHeight: '500px' }}>
            <AnimatePresence>
              {messages.map((message) => (
                <motion.div
                  key={message.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                  className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
                >
                  <div className={`max-w-[80%] ${message.sender === 'user' ? 'items-end' : 'items-start'} flex gap-3`}>
                    {message.sender === 'ai' && selectedRole && (
                      <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                        <img 
                          src={selectedRole.image} 
                          alt={selectedRole.name} 
                          className="w-full h-full object-cover"
                        />
                      </div>
                    )}
                    
                    <div>
                      <div className={`px-4 py-3 rounded-2xl ${
                        message.sender === 'user' 
                          ? 'bg-blue-600 text-white rounded-tr-none' 
                          : 'bg-gray-100 text-gray-800 rounded-tl-none'
                      }`}>
                        <p>{message.text}</p>
                      </div>
                      <p className={`text-xs mt-1 ${
                        message.sender === 'user' ? 'text-right' : ''
                      } text-gray-400`}>
                        {message.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </p>
                    </div>
                  </div>
                </motion.div>
              ))}
              
              {isLoading && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex justify-start"
                >
                  <div className="max-w-[80%] items-start flex gap-3">
                    {selectedRole && (
                      <div className="w-10 h-10 rounded-full overflow-hidden flex-shrink-0">
                        <img 
                          src={selectedRole.image} 
                          alt={selectedRole.name} 
                          className="w-full h-full object-cover"
                        />
                      </div>
                    )}
                    
                    <div className="px-4 py-3 bg-gray-100 text-gray-800 rounded-2xl rounded-tl-none">
                      <div className="flex space-x-2">
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                      </div>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
          
          <div className="p-6 border-t border-gray-100">
            <div className="flex gap-3">
              <button
                onClick={startListening}
                disabled={!selectedRole || isListening || isSpeaking || isLoading}
                className={`w-12 h-12 rounded-full flex items-center justify-center transition-all ${
                  !selectedRole 
                    ? 'bg-gray-200 cursor-not-allowed' 
                    : isListening 
                      ? 'bg-red-500 text-white animate-pulse' 
                      : 'bg-blue-100 text-blue-600 hover:bg-blue-200'
                }`}
              >
                <i className="fa-solid fa-microphone text-xl"></i>
              </button>
              
              <div className="relative flex-grow">
                <input
                  type="text"
                  value={inputText}
                  onChange={(e) => setInputText(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && sendTextMessage()}
                  placeholder={selectedRole ? "输入消息..." : "请先选择一个角色"}
                  disabled={!selectedRole || isListening || isSpeaking || isLoading}
                  className="w-full py-3 px-4 pr-12 rounded-full border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-50"
                />
                
                <button
                  onClick={sendTextMessage}
                  disabled={!inputText.trim() || !selectedRole || isListening || isSpeaking || isLoading}
                  className={`absolute right-2 top-1/2 transform -translate-y-1/2 p-2 rounded-full ${
                    !inputText.trim() || !selectedRole || isListening || isSpeaking || isLoading
                      ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                      : 'bg-blue-600 text-white hover:bg-blue-700'
                  }`}
                >
                  <i className="fa-solid fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}